#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/5/10 18:34
# @Author  : Mark
# @File    : sale_order.py
# @Software: PyCharm

# @Time    : 2025/6/30 1:29
# @Author  : wsxzy98@outlook.com
# @New     : extract_month_from_cn_date, _parse_valid_month
# @Change  : _validate_excel_data, _find_all_supplier_prices, _get_price_data

from markupsafe import Markup
from odoo import api, fields, models
from odoo.exceptions import ValidationError, UserError
import logging
from openpyxl import load_workbook
import base64
from io import BytesIO
import re, datetime

_logger = logging.getLogger(__name__)

def _parse_valid_month(valid_month):
        """解析valid_month字符串为月份int列表，支持中英文逗号和多格式"""
        if not valid_month:
            return []
        # 替换所有中文逗号为英文逗号
        month_str = valid_month.replace('，', ',')
        # 正则提取纯数字，去除"月"字或空格
        month_list = []
        for item in month_str.split(','):
            item = item.strip()
            # 去除'月'、‘月份’等
            item = re.sub(r'月|月份', '', item)
            # 如果剩下的还是数字才用
            if item.isdigit():
                month_list.append(str(int(item)))
        return month_list

def extract_month_from_cn_date(date_str):
    """
    支持‘2025年6月’、‘2025/6/1’、‘2025-06-01’、‘2025.6.1’等多种格式，返回‘6月’。
    """
    if not date_str:
        return ""
    # 兼容datetime.date/datetime类型
    if isinstance(date_str, (datetime.date, datetime.datetime)):
        return f"{date_str.month}月"
    s = str(date_str)
    # 先处理‘2025年6月’格式
    m = re.search(r"(\d{1,2})月", s)
    if m:
        return f"{int(m.group(1))}月"
    # 处理‘2025/6/1’‘2025-6-1’‘2025.6.1’
    m = re.search(r"(?:\d{4})[/-\.](\d{1,2})[/-\.]", s)
    if m:
        return f"{int(m.group(1))}月"
    # 处理‘2025/6’‘2025-6’
    m = re.search(r"(?:\d{4})[/-\.](\d{1,2})$", s)
    if m:
        return f"{int(m.group(1))}月"
    return ""

class forpro_sale_order(models.Model):
    _inherit = 'sale.order'

    customer_reference = fields.Char(string='客户参考号')
    product_quantity = fields.Integer(compute='_compute_product_quantity', string='产品总数量')
    purchase_name = fields.Many2one(
        'res.partner',
        string='供应商名称',
        domain=[('supplier_rank', '>', 0)]
    )
    file = fields.Binary(string='导入文件')
    file_name = fields.Char(string='文件名')
    product_number = fields.Text(string='产品编号')
    country_id = fields.Many2one('res.country', string='国家')
    brand_id = fields.Char('品牌')
    date_from = fields.Date(string='开始日期')
    delivery_type = fields.Selection([
        ('future', '期货'),
        ('spot', '现货')
    ])
    valid_month = fields.Char(string='有效月份')

    def action_open_purchase_order_wizard(self):
        self.ensure_one()

        if not self.purchase_name:
            raise UserError("请先选择供应商。")

        order_line_data = []
        for line in self.order_line:
            if not line.product_id or line.product_uom_qty <= 0:
                continue
            qty_to_purchase = max(line.product_uom_qty - line.qty_delivered, 0)
            order_line_data.append((0, 0, {
                'product_id': line.product_id.id,
                'product_qty': qty_to_purchase,
                'price_unit': line.purchase_price or 0.0,
                'sale_line_id': line.id,
            }))

        if not order_line_data:
            raise UserError("没有可用于生成采购单的有效销售明细行，请检查产品和数量是否正确。")

        return {
            'type': 'ir.actions.act_window',
            'name': '申请创建采购单',
            'res_model': 'purchase.order.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_sale_order_id': self.id,
                'default_partner_id': self.purchase_name.id,
                'default_customer_reference': self.customer_reference,
                'default_order_line_ids': order_line_data,
            },
        }

    def _action_confirm(self):
        res = super()._action_confirm()
        for order in self:
            purchase_orders = order._get_purchase_orders()
            for po in purchase_orders:
                po.customer_reference = order.customer_reference
            for picking in order.picking_ids:
                picking.customer_reference = order.customer_reference
        return res

    def _compute_product_quantity(self):
        for record in self:
            record.product_quantity = sum(line.product_uom_qty for line in record.order_line)

    def button_exchange(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': '税项选择',
            'view_mode': 'form',
            'res_model': 'tax.selection',
            'target': 'new',
            'context': {
                'default_order_id': self.id,
            },
        }

    @api.with_redis_client
    def action_create_product(self, redis_client=None):
        is_text_input = bool(self.product_number)

        # 如果 product_number 为空，则从文件中读取产品编码
        if not is_text_input:
            if not self.file:
                raise UserError("请上传包含产品编号的Excel文件")

            try:
                excel_data = base64.b64decode(self.file)
                wb = load_workbook(filename=BytesIO(excel_data))
                sheet = wb.active
                product_data = []

                headers = [sheet.cell(row=1, column=col).value for col in range(1, sheet.max_column + 1)]
                for row in range(2, sheet.max_row + 1):
                    row_data = {
                        headers[col_idx]: (sheet.cell(row=row, column=col_idx + 1).value or '')
                        for col_idx in range(len(headers))
                    }
                    product_data.append(row_data)

                if not product_data:
                    raise UserError("Excel文件中未找到有效数据")

            except Exception as e:
                error_msg = f"读取Excel文件失败: {str(e)}"
                _logger.error(error_msg)
                raise UserError(error_msg)

        else:
            # 文本输入模式，仅使用 Redis 查询
            product_codes = [code.strip().upper() for code in self.product_number.split('\n') if code.strip()]
            product_data = [{"产品": code} for code in product_codes]

        try:
            price_ids = self._validate_excel_data()
        except UserError as e:
            self.message_post(body=f"<p class='alert alert-danger'>{str(e)}</p>")
            return

        if not redis_client:
            self.message_post(body="<p class='alert alert-danger'>Redis连接失败</p>")
            return

        stats = {
            'total': len(product_data),
            'success': 0,
            'not_found': 0,
            #'price_missing': 0,
            'processed': [],
            'failed': []
        }

        for product_dict in product_data:
            result = self._process_product_safe(product_dict, price_ids, redis_client, is_text_input)

            if result['status'] == 'success':
                stats['success'] += 1
                stats['processed'].append(product_dict.get('产品', ''))
            elif result['status'] == 'not_found':
                stats['not_found'] += 1
                stats['failed'].append(product_dict.get('产品', ''))
            # elif result['status'] == 'no_price':
            #     stats['price_missing'] += 1
            #     stats['processed'].append(product_dict.get('产品', ''))

        self._post_import_summary(stats)

    def action_clear_order_lines(self):
        #优化版 wsxzy98@outlook.com 2025/6/10
        for order in self:
          order.order_line.unlink()
        return True

    def action_clear_order_lines1(self):
        for order in self:
            for line in order.order_line:
                try:
                    line.unlink()
                except Exception:
                    continue
        return True

    # def _validate_excel_data(self):
    #     """
    #     获取价格表数据（其中包含产品信息），不再要求产品表。
    #     """
    #     price_ids = self.env['spreadsheet.excel'].search([('category', '=', 'price')])
    #     if not price_ids:
    #         raise UserError('请先上传价格表')
    #     return price_ids
    
    #优化版
    def _validate_excel_data(self):
        """
        获取价格表数据（其中包含产品信息），按有效月份过滤
        """
        price_objs = self.env['spreadsheet.excel'].search([('category', '=', 'price')])
        valid_months = _parse_valid_month(self.valid_month)
        # 如果没选，全部
        if not valid_months:
            return price_objs
        # 否则只保留date_from月份在valid_months的
        filtered = price_objs.filtered(
            lambda rec: rec.date_from and str(int(rec.date_from.month)) in valid_months
        )
        if not filtered:
            raise UserError('没有找到有效月份的价格表！')
        return filtered

    def _get_price_data(self, redis_client, price_ids, product_code):
        """从Redis获取指定产品的价格表数据（优化版）

        Args:
            redis_client: Redis客户端
            price_ids: 价格表记录集
            product_code: 需要获取价格的产品代码
        """
        import json

        price_data = []

        for price_excel in price_ids:
            date_from = price_excel.date_from
            price_key = str(price_excel.sequence)
            raw_price = redis_client.redis_conn.hget(price_key, product_code)

            if not raw_price:
                continue

            if isinstance(raw_price, bytes):
                raw_price = raw_price.decode('utf-8')

            try:
                price_record = json.loads(raw_price)
                price_record['date_from'] = date_from
                # === 添加过滤条件 ===
                # 国家过滤（如果 sale.order 有国家）
                if self.country_id and price_record.get('国家') != self.country_id.name:
                    continue

                # 供应商过滤（如果 sale.order 有选择供应商）
                if self.purchase_name and price_record.get('供应商') != self.purchase_name.name:
                    continue

                if self.brand_id and price_record.get('品牌') != self.brand_id:
                    continue

                if self.delivery_type == 'future':
                    try:
                        stock_qty = float(price_record.get('数量', 0) or 0)
                        if stock_qty != 0:
                            continue  # 非0库存不保留
                    except (ValueError, TypeError):
                        continue  # 无法解析数量的记录跳过

                elif self.delivery_type == 'spot':
                    try:
                        stock_qty = float(price_record.get('数量', 0) or 0)
                        if stock_qty <= 0:
                            continue  # 无库存或负库存跳过
                    except (ValueError, TypeError):
                        continue  # 无法解析数量的记录跳过

                price_data.append(price_record)

            except (json.JSONDecodeError, TypeError) as e:
                _logger.warning(f"解析产品 {product_code} 的价格数据失败: {e}")

        return price_data

    def _create_or_get_product(self, record, redis_client=None):
        """
        创建或获取产品，redis主数据优先，excel补齐，其余全部兜底。
        """
        product_code = record.get('产品')
        if not product_code:
            return None

        # 1. 先查Odoo数据库（严格要求default_code唯一）
        product_id = self.env['product.product'].search([('default_code', '=', product_code)], limit=1)
        if product_id:
            return product_id

        # 2. redis主数据优先，全部字段都尝试取
        redis_data = {}
        if redis_client:
            try:
                price_ids = self.env['spreadsheet.excel'].search([('category', '=', 'price')])
                for price_excel in price_ids:
                    raw_data = redis_client.redis_conn.hget(str(price_excel.sequence), product_code)
                    if raw_data:
                        import json
                        if isinstance(raw_data, bytes):
                            raw_data = raw_data.decode('utf-8')
                        redis_data = json.loads(raw_data)
                        break
            except Exception as e:
                _logger.warning(f"从 Redis 获取产品数据失败: {e}")

        # 3. 优先级合并：redis > excel(record) > 兜底
        def pick(*args, default=None):
            for v in args:
                if v not in [None, '', 0]:
                    return v
            return default

        product_name = pick(
            redis_data.get('产品名称'), redis_data.get('描述'), record.get('产品名称'), '未命名'
        )
        brand_name = pick(
            redis_data.get('品牌'), record.get('品牌'), '未知品牌'
        )
        product_desc = pick(
            redis_data.get('描述'), record.get('描述'), ''
        )
        product_origin = pick(
            redis_data.get('原产地'), record.get('原产地'), ''
        )
        barcode = pick(
            redis_data.get('条码'), record.get('条码'), ''
        )
        ref_code = pick(
            redis_data.get('参考号'), record.get('参考号'), product_code
        )

        # 4. 创建品牌
        brand_id = self.env['gs.barnd'].search([('name', '=', brand_name)], limit=1)
        if not brand_id:
            brand_id = self.env['gs.barnd'].create({'name': brand_name})

        # 5. 新建product.template
        product_tmpl = self.env['product.template'].create({
            'name': product_name,
            'default_code': product_code,
            'barcode': barcode,
            'new_variable': record.get('替换编码/新编码', ''),
            'description': product_desc,
            'brand_id': brand_id.id,
            'origin': product_origin,
            'weight_gram': pick(record.get('克重'), 0),
            'length_cm': pick(record.get('长'), 0),
            'width_cm': pick(record.get('宽'), 0),
            'height_cm': pick(record.get('高'), 0),
            'is_storable': True,
            # 参考号如果你的模型有，可加字段
            #'ref_code': ref_code,
        })

        return product_tmpl.product_variant_id if product_tmpl else None

    def _create_or_find_supplier(self, supplier_name):
        """创建或查找供应商"""
        if not supplier_name:
            return None

        partner_id = self.env['res.partner'].search([
            ('name', '=', supplier_name),
            ('supplier_rank', '>', 0)
        ], limit=1)

        if not partner_id:
            partner_id = self.env['res.partner'].create({
                'name': supplier_name,
                'supplier_rank': 1,
                'company_type': 'company',
            })

        return partner_id

    def _update_supplier_info(self, product_id, partner_id, supplier_price):
        """更新产品的供应商价格信息"""
        supplier_info = self.env['product.supplierinfo'].search([
            ('product_tmpl_id', '=', product_id.product_tmpl_id.id),
            ('partner_id', '=', partner_id.id),
        ], limit=1)

        if not supplier_info:
            supplier_info = self.env['product.supplierinfo'].create({
                'product_tmpl_id': product_id.product_tmpl_id.id,
                'partner_id': partner_id.id,
                'price': max(supplier_price, 0.0),
                'min_qty': 1.0,
            })
        elif supplier_price > 0:
            supplier_info.price = supplier_price

        return supplier_info

    def _handle_stock_inventory(self, product_id, supplier_name):
        """处理现货库存信息"""
        location_name = f"{supplier_name} 现货库存"
        stock_location = self.env['stock.location'].search([
            ('name', '=', location_name),
            ('usage', '=', 'internal')
        ], limit=1)

        if not stock_location:
            main_stock = self.env.ref('stock.stock_location_stock')
            stock_location = self.env['stock.location'].create({
                'name': location_name,
                'location_id': main_stock.id,
                'usage': 'internal',
                'comment': f'供应商 {supplier_name} 的现货库存位置'
            })

        # 检查产品在此库位的库存情况
        quants = self.env['stock.quant'].search([
            ('product_id', '=', product_id.id),
            ('location_id', '=', stock_location.id)
        ])

        stock_qty = sum(quant.quantity for quant in quants)
        return stock_qty

    def _create_sale_line(self, product_id, product_data, sales_price=0.0, cost_price=0.0, supplier_name=None,
                          supply_type=None, supplier_info=None, supplier_list=None, custom_purchase_desc=None):
        """创建或更新销售订单行，包含所有供应商信息"""
        # 从产品数据中获取数量和Excel中的价格
        quantity = product_data.get('数量', 1)
        excel_sales_price = sales_price
        excel_cost_price = cost_price
        # 优先使用Excel中的价格
        if excel_sales_price:
            try:
                sales_price = float(excel_sales_price)
            except (ValueError, TypeError):
                pass
        
        # 组装采购描述（无拼接，无split，只覆盖）优化版
        if custom_purchase_desc is not None:
            supplier_details = custom_purchase_desc
        else:
            supplier_details = ""
            if supplier_list:
                # 检查是否全部价格为0
                all_price_zero = all(float(supplier.get('price', 0) or 0) == 0 for supplier in supplier_list)
                if all_price_zero:
                    supplier_details = "暂无价格数据"
                else:
                    for idx, supplier in enumerate(supplier_list):           
                        if idx > 0:
                            supplier_details += "\n-------\n"
                        name = supplier.get('name', '')
                        price = supplier.get('price', 0)
                        qty = supplier.get('quantity', 0)
                        raw_month = supplier.get('date_from')  # 注意字段名是date_from
                        if isinstance(raw_month, (datetime.date, datetime.datetime)):
                            month_label = f"{raw_month.month}月"
                        else:
                            month_label = extract_month_from_cn_date(raw_month)
                        lead_time = supplier.get('采购/现货', '30天')

                        if qty and float(qty) > 0:
                            # 现货
                            supplier_details += (
                                f"{name} (供应商价: €{float(price):.2f}) "
                                f"[数量: {qty} 个] [{month_label} 交期: {lead_time}]"
                            )
                        else:
                            # 期货
                            supplier_details += (
                                f"{name} (供应商价: €{float(price):.2f}) "
                                f"[{month_label} 交期: {lead_time}]"
                            )
            else:
                supplier_details = "暂无价格数据"

        # 查找是否已存在相同的产品行
        existing_line = self.env['sale.order.line'].search([
            ('order_id', '=', self.id),
            ('product_id', '=', product_id.id)
        ], limit=1)

        if existing_line:
            # 更新现有行
            update_vals = {}

            # 更新数量
            if quantity:
                try:
                    update_vals['product_uom_qty'] = float(quantity)
                except (ValueError, TypeError):
                    pass

            # 更新价格（如果销售价格有效）
            if sales_price > 0:
                update_vals['price_unit'] = sales_price

            # *****关键修改：采购描述只用新生成的supplier_details完全覆盖！*****
            if supplier_details:
                update_vals['purchase_desc'] = supplier_details.strip()
                # 精确同步成本价
                try:
                    price_text = supplier_details.split('供应商价:')[1].split(')')[0]
                    price_number = float(price_text.replace(self.currency_id.symbol, '').strip())
                    update_vals['purchase_price'] = price_number
                except Exception:
                    pass

            # 如果有需要更新的字段，执行更新
            if update_vals:
                existing_line.write(update_vals)

        else:
            # 获取正确的计量单位
            uom_id = product_id.uom_id.id or self.env.ref('uom.product_uom_unit').id

            # 准备创建明细行的数据
            try:
                qty = float(quantity) if quantity else 1.0
            except (ValueError, TypeError):
                qty = 1.0

            # 优先使用Excel中的成本价
            cost_price = excel_cost_price if excel_cost_price else 0.0
            try:
                cost_price = float(cost_price)
            except (ValueError, TypeError):
                cost_price = 0.0

            # 准备创建明细行的数据
            vals = {
                'product_template_id': product_id.product_tmpl_id.id,
                'product_id': product_id.id,
                'product_uom_qty': qty,
                'product_uom': uom_id,
                'price_unit': sales_price if sales_price > 0 else product_id.lst_price,
                'name': '', # 强制不给描述
                'purchase_desc': supplier_details.strip(),
                'order_id': self.id,
                'purchase_price': cost_price,
            }

            # 创建销售订单明细行
            self.env['sale.order.line'].create(vals)

    def _post_import_summary(self, stats):
        """生成并记录导入结果摘要"""
        summary = f"""
        <div class="alert alert-info">
            <h4>产品导入结果摘要</h4>
            <ul>
                <li>总计: <b>{stats['total']}</b> 个产品</li>
                <li>成功导入: <b>{stats['success']}</b> 个产品</li>
                <li>未找到: <b>{stats['not_found']}</b> 个产品</li>
            </ul>
        """

        # 如果有失败的产品，显示详情
        # if stats['failed']:
        #     summary += "<p>未找到的产品编号:</p><ul>"
        #     for code in stats['failed'][:10]:  # 最多显示10个
        #         summary += f"<li>{code}</li>"

        #     if len(stats['failed']) > 10:
        #         summary += f"<li>...等共 {len(stats['failed'])} 个</li>"
        #     summary += "</ul>"

        # 显示所有未找到的产品编号（不截断）
        if stats['failed']:
            summary += "<p>未找到的产品编号:</p><ul>"
            for code in stats['failed']:
                summary += f"<li>{code}</li>"
            summary += "</ul>"

        # 使用Markup包装整个HTML
        summary += "</div>"
        self.message_post(body=Markup(summary))
    
    def _process_product_safe(self, product_data, price_ids, redis_client, is_text_input=False):
        """
        处理单个产品（安全），支持销售订单导入/手动输入，自动判断delivery_type和价格表情况。

        主要业务规则：
        1. 文本输入模式：优先查redis，查不到再查产品库，有就生成，无就右侧chatter汇总。
        2. Excel导入模式：excel有产品就一定生成订单行，redis数据只做采购描述和补值，没数据就写“暂无供应商数据，等待补充”。
        3. 价格优先excel，无则redis，无则0。
        """

        product_code = product_data.get('产品', '')
        if not product_code:
            return {'status': 'not_found', 'message': '产品编码为空'}

        try:
            # 1. 文本输入模式（优先查redis，再查产品库）
            if is_text_input:
                # 1.1 redis查价
                price_records = self._get_price_data(redis_client, price_ids, product_code)
                if price_records:
                    product_id = self._create_or_get_product(product_data, redis_client)
                    if product_id:
                        price_info, all_suppliers = self._find_all_supplier_prices(price_records)
                        return self._handle_supplier_and_create_line(
                            product_id, product_data, price_info, all_suppliers
                        ) or {'status': 'success', 'message': f"Redis 创建产品 {product_code}"}
                    else:
                        return {'status': 'not_found', 'message': f"无法创建产品 {product_code}"}
                # 1.2 查Odoo产品库
                product_id = self.env['product.product'].search([('default_code', '=', product_code)], limit=1)
                if product_id:
                    self._create_sale_line(
                        product_id, product_data, 0, 0, None, None, None, None,
                        custom_purchase_desc="暂无供应商数据，等待补充"
                    )
                    return {'status': 'success', 'message': f"产品库创建产品 {product_code}（无redis数据）"}
                # 1.3 都没有只汇总到chatter
                return {'status': 'not_found', 'message': f"未找到产品 {product_code}"}

            # 2. Excel导入模式
            # 2.1 先查Odoo产品库，查不到就自动新建（允许新建！）
            product_id = self.env['product.product'].search([('default_code', '=', product_code)], limit=1)
            if not product_id:
                product_id = self._create_or_get_product(product_data, redis_client)
                if not product_id:
                    return {'status': 'not_found', 'message': f'无法创建产品 {product_code}'}

            # 2.2 获取excel单价
            excel_sales_price = product_data.get('销售单价')
            excel_cost_price = product_data.get('成本单价')
            try:
                excel_sales_price = float(excel_sales_price) if excel_sales_price not in [None, '', 0] else None
            except Exception:
                excel_sales_price = None
            try:
                excel_cost_price = float(excel_cost_price) if excel_cost_price not in [None, '', 0] else None
            except Exception:
                excel_cost_price = None

            # 2.3 查询redis数据（不决定生成行，仅用来补值和采购描述）
            price_records = self._get_price_data(redis_client, price_ids, product_code)

            if price_records:
                price_info, all_suppliers = self._find_all_supplier_prices(price_records)
                redis_sales_price = float(price_info.get('销售价格') or 0) if price_info else 0.0
                redis_cost_price = float(price_info.get('供应商价格') or 0) if price_info else 0.0
                final_sales_price = excel_sales_price if excel_sales_price is not None else redis_sales_price
                final_cost_price = excel_cost_price if excel_cost_price is not None else redis_cost_price
                purchase_desc = None  # 用all_suppliers生成，留空用默认规则
                supplier_list = all_suppliers
            else:
                # redis无数据时，采购描述写固定文案，价格只用excel，无则为0
                final_sales_price = excel_sales_price if excel_sales_price is not None else 0.0
                final_cost_price = excel_cost_price if excel_cost_price is not None else 0.0
                purchase_desc = "暂无供应商数据，等待补充"
                supplier_list = None

            # 2.4 创建订单行
            self._create_sale_line(
                product_id, product_data, final_sales_price, final_cost_price,
                None, None, None, supplier_list, custom_purchase_desc=purchase_desc
            )

            # 2.5 如需写供应商关联，可保留这段
            supplier_name = self.purchase_name.name if self.purchase_name else product_data.get('供应商', '')
            if supplier_name:
                partner_id = self._create_or_find_supplier(supplier_name)
                self._update_supplier_info(product_id, partner_id, final_cost_price)

            return {'status': 'success', 'message': f"生成订单行: {product_code}"}

        except Exception as e:
            error_msg = f"处理产品 {product_code} 时出错: {str(e)}"
            _logger.exception(error_msg)
            return {'status': 'error', 'message': error_msg}

    def _find_all_supplier_prices(self, price_records):
        """查找所有供应商价格并返回最优选项及所有供应商列表"""
        best_supplier_info = None
        lowest_supplier_price = float('inf')
        is_stock_found = False
        all_suppliers = []

        # 处理供应商信息
        for price_info in price_records:
            try:
                supplier_name = price_info.get('供应商', '')
                if not supplier_name:
                    continue

                # 获取价格信息，即使价格为0也处理
                try:
                    supplier_price = float(price_info.get('供应商价格', 0))
                except (ValueError, TypeError):
                    supplier_price = 0.0

                try:
                    sales_price = supplier_price / 1.2
                except (ValueError, TypeError):
                    sales_price = 0.0

                supply_type = price_info.get('采购/现货', '')
                is_in_stock = supply_type and '现货' in supply_type
                days = price_info.get('天数', '未知')
                quantity = price_info.get('数量', '0')

                # 构建供应商信息 - 无论价格是否为0都添加
                supplier_info = {
                    'name': supplier_name,
                    'price': supplier_price,
                    'sales_price': sales_price,
                    'is_stock': is_in_stock,
                    'type': supply_type,
                    'days': days,
                    'quantity': quantity,
                    'date_from': price_info.get('date_from')  # 只要price_info有date_from字段
                }
                all_suppliers.append(supplier_info)

                # 选择最佳供应商 - 现货优先，其次价格最低
                if is_in_stock:
                    if not is_stock_found or supplier_price < lowest_supplier_price:
                        lowest_supplier_price = supplier_price
                        best_supplier_info = price_info
                        is_stock_found = True
                elif not is_stock_found:
                    # 没有现货时，选择采购类型中价格最低的
                    if best_supplier_info is None or supplier_price < lowest_supplier_price:
                        lowest_supplier_price = supplier_price
                        best_supplier_info = price_info

            except Exception as e:
                _logger.warning(f"处理供应商信息时出错: {e}")
                continue

        # 如果没有找到最佳供应商但有供应商列表，选择第一个作为最佳选择
        if best_supplier_info is None and all_suppliers:
            best_supplier_info = price_records[0] if price_records else None

        # 按价格排序，现货优先
        all_suppliers.sort(key=lambda x: (0 if x['is_stock'] else 1, x['price']))

        return best_supplier_info, all_suppliers

    def _handle_supplier_and_create_line(self, product_id, product_data, price_info, all_suppliers):
        """处理供应商信息并创建销售订单行，包含更多供应商详情"""
        # 解析主要供应商信息
        try:
            sales_price = float(price_info.get('销售价格', 0))
        except (ValueError, TypeError):
            sales_price = 0.0

        try:
            supplier_price = float(price_info.get('供应商价格', 0))
        except (ValueError, TypeError):
            supplier_price = 0.0

        supplier_name = price_info.get('供应商')
        supply_type = price_info.get('采购/现货')

        # 处理主要供应商信息
        primary_supplier_info = None
        if supplier_name:
            partner_id = self._create_or_find_supplier(supplier_name)
            primary_supplier_info = self._update_supplier_info(product_id, partner_id, supplier_price)

            # 如果是现货，检查或创建库存
            if supply_type and '现货' in supply_type:
                self._handle_stock_inventory(product_id, supplier_name)

        # 创建或更新销售订单行，包含所有供应商信息
        self._create_sale_line(product_id, product_data, sales_price, supplier_price,
                               supplier_name if primary_supplier_info else None,
                               supply_type, primary_supplier_info, all_suppliers)
